package com.ruyuan.payment.server.service;

import com.ruyuan.payment.server.domain.OrderInfo;
import com.ruyuan.payment.server.domain.OrderInfoExample;
import com.ruyuan.payment.server.domain.OrderPay;
import com.ruyuan.payment.server.domain.OrderPayExample;
import com.ruyuan.payment.server.enums.OrderInfoBusinessEnum;
import com.ruyuan.payment.server.enums.OrderInfoStatusEnum;
import com.ruyuan.payment.server.enums.OrderPayStatusEnum;
import com.ruyuan.payment.server.mapper.OrderInfoMapper;
import com.ruyuan.payment.server.mapper.OrderPayMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

@Service
public class PaySuccessService {

    private static final Logger LOG = LoggerFactory.getLogger(PaySuccessService.class);

    @Resource
    private OrderPayService orderPayService;

    @Resource
    private OrderPayMapper orderPayMapper;

    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Resource
    private AccountService accountService;

    public void afterPaySuccess(String payNo, Date channelTime) {
        LOG.info("支付成功后处理开始：payNo：{}，channelTime：{}", payNo, channelTime);
        Date now = new Date();

        LOG.info("更新支付订单为支付成功：payNo：{}", payNo);
        OrderPay orderPayDB = orderPayService.selectByPayNo(payNo);
        if (updateOrderPay(payNo, channelTime, now, orderPayDB)) {
            return;
        }

        String orderNo = orderPayDB.getOrderNo();
        LOG.info("更新商品订单为支付成功：orderNo：{}", orderNo);
        OrderInfo orderInfoDB = orderInfoService.selectByOrderNo(orderNo);
        if (updateOrderInfo(now, orderNo, orderInfoDB)) {
            return;
        }

        if (orderInfoDB.getBusiness().equals(OrderInfoBusinessEnum.DEPOSIT.getCode())) {
            // 余额充值
            accountService.doAccount(orderPayDB.getMemberId(), orderInfoDB.getAmount(), "余额充值" + orderInfoDB.getAmount() + "元");
        } else if (orderInfoDB.getBusiness().equals(OrderInfoBusinessEnum.COURSE.getCode())) {
            if (orderPayDB.getAccountAmount().compareTo(BigDecimal.ZERO) > 0
            && orderPayDB.getChannelAmount().compareTo(BigDecimal.ZERO) > 0) {
                // 解冻并扣款
                accountService.unfreezeAndDoAccount(orderPayDB.getMemberId(), orderPayDB.getAccountAmount(), payNo);
            }
            // 通知业务系统支付成功 TODO
            LOG.info("通知业务系统支付成功");
        } else {
            LOG.error("业务通知异常");
        }

    }

    private boolean updateOrderInfo(Date now, String orderNo, OrderInfo orderInfoDB) {
        orderInfoDB.setStatus(OrderInfoStatusEnum.SUCCESS.getCode());
        orderInfoDB.setUpdatedAt(now);
        OrderInfoExample orderInfoExample = new OrderInfoExample();
        orderInfoExample.createCriteria().andIdEqualTo(orderInfoDB.getId())
                .andStatusEqualTo(OrderInfoStatusEnum.INIT.getCode());
        int j = orderInfoMapper.updateByExample(orderInfoDB, orderInfoExample);
        if (j == 0) {
            LOG.info("防重拦截：商品订单状态非初始：orderNo：{}，status：{}", orderNo, orderInfoDB.getStatus());
            return true;
        }
        return false;
    }

    private boolean updateOrderPay(String payNo, Date channelTime, Date now, OrderPay orderPayDB) {
        orderPayDB.setChannelTime(channelTime);
        orderPayDB.setStatus(OrderPayStatusEnum.SUCCESS.getCode());
        orderPayDB.setUpdatedTime(now);
        OrderPayExample orderPayExample = new OrderPayExample();
        orderPayExample.createCriteria().andIdEqualTo(orderPayDB.getId())
                .andStatusEqualTo(OrderPayStatusEnum.INIT.getCode());
        int i = orderPayMapper.updateByExample(orderPayDB, orderPayExample);
        if (i == 0) {
            LOG.info("防重拦截：支付订单状态非初始：payNo：{}，status：{}", payNo, orderPayDB.getStatus());
            return true;
        }
        return false;
    }
}
